/*
 * Copyright 2023 AntGroup CO., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

package com.antgroup.geaflow.console.common.dal.datasource;

import com.antgroup.geaflow.console.common.dal.dao.TenantLevelExtDao;
import com.antgroup.geaflow.console.common.util.Fmt;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

public class GeaflowTenantInterceptor extends TenantLineInnerInterceptor {

    public GeaflowTenantInterceptor(TenantLineHandler tenantLineHandler) {
        super(tenantLineHandler);
    }

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds,
                            ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        if (ignoreSql(boundSql.getSql())) {
            return;
        }

        super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
    }

    @Override
    public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
        if (ignoreSql(PluginUtils.mpStatementHandler(sh).boundSql().getSql())) {
            return;
        }

        super.beforePrepare(sh, connection, transactionTimeout);
    }

    private static boolean ignoreSql(String sql) {
        return sql.endsWith(Fmt.as("/*{}*/", TenantLevelExtDao.IGNORE_TENANT_SIGNATURE));
    }
}
